package gamesys.games.particlesystem.utils
{
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;

	/**
	 * @author robt
	 */
	public class BitmapUtils
	{
		/* getBitmapDataFromMovieClip
		 * 
		 * Returns any given frame of a MovieClip as a bitmapdata
		 * Bounds are needed as each frame of a MovieClip has different bounds
		 * The bounds for each frame would need to be the same (the max bounds of all frames) in order for the bitmapdata to appear in the correct place
		 * Use getAccumulatedBounds to get the bounds of all frames
		 */
		public static function getBitmapDataFromMovieClip(source:MovieClip, frame:int, bounds:Rectangle):BitmapData
		{
			var bitmapData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x00000000);
			var matrix:Matrix = new Matrix(1, 0, 0, 1, -bounds.x, -bounds.y);

			source.gotoAndStop(frame);
			bitmapData.draw(source, matrix);

			return bitmapData;
		}

		/* getAccumulatedBounds
		 * 
		 * Calculates the largest bounds needed for all frames in the source MoviClip
		 */
		public static function getAccumulatedBounds(source:MovieClip):Rectangle
		{
			var bounds:Rectangle;
			var boundsToCheck:Rectangle;

			for (var i:int = 0;i < source.totalFrames;i++)
			{
				source.gotoAndStop(i + 1);
				boundsToCheck = source.getBounds(source);

				if (i == 0)
				{
					bounds = new Rectangle(boundsToCheck.x, boundsToCheck.y, boundsToCheck.width, boundsToCheck.height);
				}
				else
				{
					bounds.x = Math.min(boundsToCheck.x, bounds.x);
					bounds.y = Math.min(boundsToCheck.y, bounds.y);
					bounds.width = Math.max(boundsToCheck.width + boundsToCheck.x, bounds.width);
					bounds.height = Math.max(boundsToCheck.height + boundsToCheck.y, bounds.height);
				}
			}

			bounds.width += -bounds.x;
			bounds.height += -bounds.y;

			return bounds;
		}
	}
}